package com.lenovo.smarttraffic.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.zm.Bean.SenseBean;
import com.lenovo.smarttraffic.zm.Bean.TempBean;
import com.lenovo.smarttraffic.zm.Item2Activity;
import com.lenovo.smarttraffic.zm.OkHttpUtils1;
import com.lenovo.smarttraffic.zm.StopCarActivity;
import com.lenovo.smarttraffic.zm_user_module.User_centerActivity;
import com.lenovo.smarttraffic.zm_Set.User_SignInActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * @author Amoly
 * @date 2020/0604    不追求代码简洁     时间不够   容易出错  zm
 * description：主页面
 */
public class MainContentFragment extends BaseFragment {
    private static MainContentFragment instance = null;
    private String urlMainSense = "http://192.168.1.110:8088/transportservice/action/GetAllSense.do";
    public String urlMainTemp = "http://192.168.1.110:8088/transportservice/action/GetWeather.do";
    String TAG = "MainContentFragment";
    private PieChart pie;

    private TextView second_temp;
    List<PieEntry> V = new ArrayList<>();
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 3000);
            initPieData();
        }
    };
    private int pm;
    private RelativeLayout Rl_urban_subway,Rl_user_center,Rl_park_search,Rl_User_SignIn;
    private String account;
    SharedPreferences sharedPreferences;
    private TextView tv_LightIntensity;
    private TextView tv_co2;
    private TextView tv_temperature;
    private TextView tv_humidity, tv_one, type_change, tv_second;
    private SenseBean senseBean;
    public TempBean tempBean;
    private RelativeLayout rl_user_center;

    public static MainContentFragment getInstance() {
        if (instance == null) {
            instance = new MainContentFragment();
        }
        return instance;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_home, null);
        sharedPreferences = getActivity().getSharedPreferences("LoginFlag", Context.MODE_PRIVATE);
        if (InitApp.isRegister) {
            account = sharedPreferences.getString("account", "为记住密码");
            //登陆未记住密码
            if (account.equals("为记住密码")) {
                account = InitApp.UserName;
            }
            Log.e(TAG, "success: 登陆");
        } else {
            account = "user1";
            Log.e(TAG, "success: 未登录");
        }
        initView(view);
        initPieData();
        okHttpUtils();
        handler.post(runnable);

        return view;
    }

    private void initView(View view) {




        //天气  网络请求  数据
        //饼状图
        pie = view.findViewById(R.id.mainPagePie_env);
        second_temp = view.findViewById(R.id.second_temp_type);
        type_change = view.findViewById(R.id.type_change);
        tv_LightIntensity = (TextView) view.findViewById(R.id.tv_LightIntensity);
        tv_co2 = (TextView) view.findViewById(R.id.tv_co2);
        tv_temperature = (TextView) view.findViewById(R.id.tv_temperature);
        tv_humidity = (TextView) view.findViewById(R.id.tv_humidity);




        //上面两个  天气的跳转
        tv_one = view.findViewById(R.id.tv_one);
        tv_second = view.findViewById(R.id.tv_second);
        tv_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), Item2Activity.class));
            }
        });
        tv_second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), Item2Activity.class));
            }
        });


        //下面四个   消费中心  用户中心   用户签到  城市地铁   跳转
        Rl_urban_subway = view.findViewById(R.id.Rl_urban_subway);
        Rl_park_search = view.findViewById(R.id.Rl_park_search);
        Rl_user_center = view.findViewById(R.id.Rl_user_center);
        Rl_User_SignIn = view.findViewById(R.id.Rl_User_SignIn);
        Rl_urban_subway.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        Rl_park_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), StopCarActivity.class));
            }
        });
        Rl_user_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), User_centerActivity.class));

            }
        });
        Rl_User_SignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), User_SignInActivity.class));
            }
        });
    }


    private void initPieData() {
        pm = new Random().nextInt(390) + 10;
        //  pm=senseBean.get_$Pm25291();
        pie.setDescription(null);
        pie.setEnabled(false);
        pie.setClickable(false);
        pie.setHighlightPerTapEnabled(false);
        pie.setDrawHoleEnabled(true);
        pie.setRotationEnabled(false);
        pie.setEntryLabelColor(Color.BLACK);
        pie.setHoleRadius(70);
        pie.setDrawCenterText(true);
        pie.setCenterTextColor(Color.BLACK);
        pie.getLegend().setEnabled(false);
        if (pm < 35) {
            pie.setCenterText("优");
        } else if (pm >= 35 && pm <= 75) {
            pie.setCenterText("良");
        } else if (pm > 75 && pm < 115) {
            pie.setCenterText("轻度污染");
        } else if (pm >= 115 && pm <= 150) {
            pie.setCenterText("中度污染");
        } else {
            pie.setCenterText("重度污染");
        }
        V.clear();
        V.add(new PieEntry(pm, ""));
        V.add(new PieEntry(300, ""));
        PieDataSet dataSet = new PieDataSet(V, "");
        dataSet.setSliceSpace(1);
      //  dataSet.setHighlightEnabled(false);
        dataSet.setColors(Color.RED, Color.GREEN);
        dataSet.setDrawValues(false);
        pie.setData(new PieData(dataSet));
        pie.notifyDataSetChanged();
        pie.invalidate();
    }

    private void okHttpUtils() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName", account);
            OkHttpUtils1.doRequest(urlMainSense, jsonObject.toString(), new OkHttpUtils1.OnResLis() {
                @Override
                public void success(String result) {
                    Gson gson = new Gson();
                    senseBean = gson.fromJson(result, SenseBean.class);
                    chage();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils1.answer = null;
        okhttp2();
    }


    private void okhttp2() {
        JSONObject object = new JSONObject();
        try {
            object.put("UserName", account);
            OkHttpUtils1.doRequest(urlMainTemp, object.toString(), new OkHttpUtils1.OnResLis() {
                @Override
                public void success(String result) {
                    Gson gson = new Gson();
                    tempBean = gson.fromJson(result, TempBean.class);
                    if (null == tempBean.getROWS_DETAIL()) {
                        tv_one.setText("今日天气 " + 25 + "°C");
                        tv_second.setText("明日天气" + 14 + "°C");
                        icon(second_temp, "晴");
                        second_temp.setText("晴");
                        type_change.setText("晴转晴");
                        icon(type_change, "晴");
                    } else {
                        tv_one.setText("今日天气 " + tempBean.getWCurrent() + "°C");
                        tv_second.setText("明日天气" + tempBean.getROWS_DETAIL().get(1).getTemperature() + "°C");
                        icon(second_temp, tempBean.getROWS_DETAIL().get(1).getType());
                        second_temp.setText(tempBean.getROWS_DETAIL().get(1).getType());
                        type_change.setText(tempBean.getROWS_DETAIL().get(0).getType() + "转" + tempBean.getROWS_DETAIL().get(1).getType());
                        icon(type_change, tempBean.getROWS_DETAIL().get(0).getType());
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected View getSuccessView() {
        View view = View.inflate(getActivity(), R.layout.fragment_home, null);
        //事件监听
        setListener(view);
        return view;
    }


    private void setListener(View view) {
    }

    @Override
    protected Object requestData() {
        return Constant.STATE_SUCCEED;
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onDestroy() {
        if (instance != null) {
            instance = null;
        }
        super.onDestroy();
    }

    public void chage() {
        tv_LightIntensity.setText(senseBean.getLightIntensity() + "");
        tv_co2.setText(senseBean.getCo2() + "");
        tv_temperature.setText(senseBean.getTemperature() + "");
        tv_humidity.setText(senseBean.getHumidity() + "");
        if (senseBean.getLightIntensity() < 1000) {
            tv_LightIntensity.setTextColor(Color.parseColor("#4472c4"));
            tv_LightIntensity.setText("弱");
        } else if (senseBean.getLightIntensity() <= 3000) {
            tv_LightIntensity.setTextColor(Color.parseColor("#00b050"));
            tv_LightIntensity.setText("中等");
        } else if (senseBean.getLightIntensity() > 3000) {
            tv_LightIntensity.setTextColor(Color.parseColor("#ff0000"));
            tv_LightIntensity.setText("强");
        }
        if (senseBean.getHumidity() < 50) {
            tv_humidity.setTextColor(Color.parseColor("#ff0000"));
            tv_humidity.setText("较易发");
        } else if (senseBean.getHumidity() >= 50) {
            tv_humidity.setTextColor(Color.parseColor("#ffff40"));
            tv_humidity.setText("少发");
        }
        if (senseBean.getTemperature() < 12) {
            tv_temperature.setTextColor(Color.parseColor("#3462f4"));
            tv_temperature.setText("冷");
        } else if (senseBean.getTemperature() <= 21) {
            tv_temperature.setTextColor(Color.parseColor("#92d050"));
            tv_temperature.setText("舒适");
        } else if (senseBean.getTemperature() < 35) {
            tv_temperature.setTextColor(Color.parseColor("#44dc68"));
            tv_temperature.setText("温暖");
        } else if (senseBean.getTemperature() > 35) {
            tv_temperature.setTextColor(Color.parseColor("#ff0000"));
            tv_temperature.setText("热");
        }
        if (senseBean.getCo2() < 3000) {
            tv_co2.setTextColor(Color.parseColor("#44dc68"));
            tv_co2.setText("适宜");
        } else if (senseBean.getCo2() <= 6000) {
            tv_co2.setTextColor(Color.parseColor("#ffc000"));
            tv_co2.setText("中");
        } else if (senseBean.getCo2() > 6000) {
            tv_co2.setTextColor(Color.parseColor("#8149ac"));
            tv_co2.setText("较不宜");
        }
    }

    public void icon(TextView tv, String type) {
        if (type.equals("晴")) {
            Drawable drawable = getResources().getDrawable(R.mipmap.sun);
            tv.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        } else if (type.equals("小雨")) {
            Drawable drawable = getResources().getDrawable(R.mipmap.rain);
            tv.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        } else if (type.equals("阴")) {
            Drawable drawable = getResources().getDrawable(R.mipmap.cloudy_);
            tv.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        }
    }

}
